define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            $(".btn-add").data('area',["100%",'100%']);
            $(".btn-edit").data('area',["100%",'100%']);
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'purchase/order/index' + location.search,
                    // add_url: 'purchase/order/add',
                    edit_url: 'purchase/order/edit',
                    // del_url: 'purchase/order/del',
                    // multi_url: 'purchase/order/multi',
                    table: 'purchase_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                rowStyle:function(row, index){
                    if (row.ystatus == 6) {
                        return{
                            css:{
                                color:'red'
                            }
                        }
                    }else{
                        return{}
                    }
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),class:'oid'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'number', title: __('Number')},

                        {field: 'nickname', title: __('Supplier_id')},
                        {field: 'name', title: __('Name'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=1")},
                        // {field: 'settle_id', title: __('Settle_id')},
                        {field: 'operator', title: __('Operator')},
                        {field: 'company', title: __('Company')},
                        {field: 'goods_name', title: __('商品名称'), visible: false},
                        {field: 'goods_number', title: __('商品编号'), visible: false},
                        // {field: 'admin_id', title: __('Admin_id')},
                        {field: 'order_goods_total', title: __('Order_goods_total'),operate:false},
                        // {field: 'lock_library_total', title: __('Lock_library_total')},
                        {field: 'arrival_total', title: __('Arrival_total'),operate:false},
                        {field: 'order_price', title: __('Order_price'), operate:'BETWEEN',operate:false},
                        {field: 'arrival_price', title: __('Arrival_price'), operate:'BETWEEN',operate:false},
                        // {field: 'paid_in_price', title: __('Paid_in_price'), operate:'BETWEEN'},
                        {field: 'status', title: __('Status'),searchList: $.getJSON(Config.this_url+"/config/zaxconfig?states=2"), sortable: true,
                            // cellStyle:function(value,row,index){
                            //     return{
                            //         css:{
                            //             "min-width":"120px"
                            //         }
                            //     }
                            // }
                            },
                        {field: 'explain', title: __('Explain'),operate:false},
                        // {field: 'abstract', title: __('Abstract'),operate:false},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            buttons: [
                                {
                                    name: 'examine',
                                    title: __('采购单审核'),
                                    classname: 'btn btn-xs btn-success btn-click editstatus',
                                    icon: 'fa fa-random',
                                    hidden:function(row){
                                        if(row.ystatus != 1){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var oid = $(this).parents('tr').find('.oid').html()
                                        var url = Config.this_url+'/purchase/order/detail?ids='+oid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "采购详情",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })

                                    }},
                                {
                                    name: 'enter',
                                    title: __('采购单入库'),
                                    classname: 'btn btn-xs btn-success btn-click editstatus',
                                    icon: 'fa fa-level-down',
                                    hidden:function(row){
                                        if(row.ystatus == 4 || row.ystatus == 1 || row.ystatus == 9|| row.ystatus == 5|| row.ystatus == 6){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var oid =$(this).parents('tr').find('.oid').html()

                                        var url = Config.this_url+'/purchase/order/enter?ids='+oid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "采购入库",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'forceend',
                                    title: __('强制完结'),
                                    classname: 'btn btn-xs btn-danger btn-click forceend',
                                    icon: 'fa fa-gavel',
                                    hidden:function(row){
                                        if(row.ystatus !=3){
                                            return true;
                                        }
                                    },
                                    click: function(data){
                                        var oid =$(this).parents('tr').find('.oid').html()

                                        var url = Config.this_url+'/purchase/order/forceend?ids='+oid
                                        layer.open({
                                            type: 2, // 1-在content中写html代码， 2-在content中写src路径
                                            area: ['80%', '90%'],
                                            title: "强制完结",
                                            content: url,
                                            // content: Config.this_url+'/purchase/requisition',
                                        })
                                    }},
                                {
                                    name: 'import',
                                    title: __('导出'),
                                    classname: 'btn btn-xs btn-warning btn-click editstatus',
                                    icon: 'fa fa-upload',
                                    hidden:function(row){

                                    },
                                    click: function(data){
                                        var oid =$(this).parents('tr').find('.oid').html()
                                        window.open(Config.this_url+'/purchase/order/import?ids='+oid)
                                    }},
                                {
                                    name: 'printing',
                                    title: __('打印'),
                                    classname: 'btn btn-xs btn-warning btn-click editstatus',
                                    icon: 'fa fa-print',
                                    hidden:function(row){

                                    },
                                    click: function(data){
                                        var oid =$(this).parents('tr').find('.oid').html()
                                        window.open(Config.this_url+'/purchase/order/printing?ids='+oid)
                                    }},
                                // {
                                //     name: 'returnorder',
                                //     title: __('采购退货'),
                                //     classname: 'btn btn-xs btn-success btn-click editstatus',
                                //     icon: 'fa fa-level-up',
                                //     hidden:function(row){
                                //         if(row.ystatus != 4){
                                //             return true;
                                //         }
                                //     },
                                //     click: function(data){
                                //         var oid =$(this).parents('tr').find('.oid').html()
                                //     }},
                                // {
                                //     name: 'returnorder',
                                //     title: __('采购退货'),
                                //     classname: 'btn btn-xs btn-success btn-click editstatus',
                                //     icon: 'fa fa-exchange',
                                //     hidden:function(row){
                                //         if(row.ystatus != 4){
                                //             return true;
                                //         }
                                //     },
                                //     click: function(data){
                                //         var oid =$(this).parents('tr').find('.oid').html()
                                //     }}
                            ],
                            events: Table.api.events.operate,
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true)
                                if(row.ystatus != 1){
                                    $(table).data("operate-edit", null);
                                }
                                $(table).data("operate-del", null); // 列表页面隐藏 .编辑operate-edit - 删除按钮operate-del
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });
            $('table').on('dblclick','td',function(){
                if($(this).parents('tr').find('.btn-editone').length >0){
                    return  false;
                }
                var oid = $(this).parents('tr').find('.oid').html()
                var url = Config.this_url+'/purchase/order/detail?ids='+oid
                layer.open({
                    type: 2, // 1-在content中写html代码， 2-在content中写src路径
                    area: ['80%', '90%'],
                    title: "采购详情",
                    content: url,
                    // content: Config.this_url+'/purchase/requisition',
                })
            });
            table.on('post-body.bs.table',function(){
                $(".btn-editone").data("area",["100%","100%"]);
            })
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            $('.freight').click(function () {
                if($('input').is('.gids'+1)){
                    layer.msg('运费已添加')
                    return false;
                }else{
                    var url = Config.this_url+'/purchase/order/getfreight'
                    $.post(url,{},function (res) {
                        var str = ''
                        str = '<tr data-index="0">\n' +
                            '<td style="text-align: center; vertical-align: middle; "><input name="row['+res.data.id+'][goods_id]" value="'+res.data.id+'" style="display: none" class="gids'+res.data.id+'">'+res.data.id+'</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">'+res.data.number+'</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; " ></td>\n' +
                            '<td style="text-align: center; vertical-align: middle; " class="title">'+res.data.title+'</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">'+res.data.place_origin+'</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">'+res.data.specs+'</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">0</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">0</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; " class="xxgg">\n' +
                            '    <input type="hidden" class="requisition_num" name="row['+res.data.id+'][goods_num]" value="1">1</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; ">台</td>\n' +
                            '<td style="text-align: center; vertical-align: middle; " class="">\n' +
                            '    <input type="text" class="form-control" style="display: none" value="" name="row['+res.data.id+'][unit_price]" onkeyup="checkInputIntFloat(this);">\n' +
                            '     <span class=" price">0</span>\n' +
                            ' </td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="allprice">0</td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="xxgg">\n' +
                            '     <input type="text" class="form-control" style="display: none" value="" name="row['+res.data.id+'][tax]">\n' +
                            '     <span class="tax ">0</span>\n' +
                            ' </td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="xxgg">\n' +
                            '  <input type="text" class="form-control ht_prices" style="display: none" value="" name="row['+res.data.id+'][ht_price]">\n' +
                            '   <span class="ht_price">0</span>\n' +
                            '  </td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="taxall">0.00</td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="sfhj">0</td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; " class="xxgg">\n' +
                            '      <input type="text" class="form-control" style="display: none" value="" name="row['+res.data.id+'][remark]">\n' +
                            '     <span class="tremark "></span></td>\n' +
                            ' <td style="text-align: center; vertical-align: middle; ">\n' +
                            '     <a href="javascript:;" class="btn btn-xs btn-danger btn-delone" data-toggle="tooltip" title="" data-table-id="table" data-field-index="15" data-row-index="0" data-button-index="2" data-original-title="删除">\n' +
                            '   <i class="fa fa-trash"></i>\n' +
                            ' </a>\n' +
                            '</td>\n' +
                            ' </tr>';
                        $('.connnn').append(str)
                    })
                }
            })
            // $(".btn-add").click(function () {
            //
            //     layer.open({
            //         type: 2, // 1-在content中写html代码， 2-在content中写src路径
            //         area: ['70%', '90%'],
            //         title: "选择请购单",
            //         content: 'choose',
            //         // content: Config.this_url+'/purchase/requisition',
            //     })
            // })
            Controller.api.bindevent();
        },
        choose:function(){
            Table.api.init();
            this.table.first();
            this.table.second();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        detail: function () {
            $('.cancelbill').click(function () {
                var url =  Config.this_url+'/purchase/order/cancelbill'+location.search
                layer.prompt({title: '输入红冲原因', formType: 2}, function(pass, index){
                    if(pass == ''){
                        layer.msg('不能为空');
                        return false;
                    }
                    $.post(url,{reason:pass},function (res) {
                        layer.msg(res.msg)
                        if(res.code == 1){
                            layer.close(index);
                            setTimeout(function () {
                                location.reload();
                            }, 800);
                            window.parent.$(".toolbar .btn-refresh").trigger('click');
                        }
                    })
                });
            })



            $('.subpurchase').click(function () {
                layer.confirm('审核通过？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                        var url = Config.this_url+'/purchase/order/examine?ids='+$('#order_id').val()
                        $.post(url,{status:2},function (res) {
                            layer.msg(res.msg)
                            if(res.code == 1){
                                parent.$(".btn-refresh").trigger("click");
                                var index = parent.Layer.getFrameIndex(window.name);
                                parent.Layer.close(index);
                            }
                        })
                }, function(){

                });
            })
            $('.reject').click(function () {
                layer.confirm('审核驳回？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    var url = Config.this_url+'/purchase/order/examine?ids='+$('#order_id').val()
                    $.post(url,{status:5},function (res) {
                        layer.msg(res.msg)
                        if(res.code == 1){
                            parent.$(".btn-refresh").trigger("click");
                            var index = parent.Layer.getFrameIndex(window.name);
                            parent.Layer.close(index);
                        }
                    })
                }, function(){

                });
            })
            $('.printing').click(function () {
                var url = Config.this_url+'/purchase/order/printing?ids='+$('#order_id').val()
                window.open(url)
            })

            // $('.reject').click(function () {
            //     layer.confirm('驳回该采购单？', {
            //         btn: ['确定','取消'] //按钮
            //     }, function(){
            //         var url = Config.this_url+'/purchase/order/examine?ids='+$('#order_id').val()
            //         $.post(url,{status:9},function (res) {
            //             layer.msg(res.msg)
            //             if(res.code == 1){
            //                 parent.$(".btn-refresh").trigger("click");
            //                 var index = parent.Layer.getFrameIndex(window.name);
            //                 parent.Layer.close(index);
            //             }
            //         })
            //     }, function(){
            //
            //     });
            // })

            Controller.api.bindevent();
        },
        enter: function () {
            Controller.api.bindevent();
        },
        forceend: function () {
            // $('.forceend').click(function () {
            //     var url = 'purchase/order/forceend'+location.search
            //     $.post(url,{},function () {
            //
            //     })
            //     console.log(location.search)
            // })
            $('.forceend').click(function () {
                layer.confirm('确定完结该采购单么？<br>完结以当前入库数量为准<br>如财务已结清账款,请移步费用单处理', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                        var url = 'purchase/order/forceend'+location.search
                        $.post(url,{},function (res) {
                            layer.msg(res.msg, {icon: 1});
                            if(res.code == 1){
                                layer.close(index);
                                setTimeout(function () {
                                    location.reload();
                                }, 800);
                                window.parent.$(".toolbar .btn-refresh").trigger('click');
                            }
                        })
                }, function(){
                    layer.msg('的确三思很重要', {icon: 1});
                });
            })
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {//渲染的方法
                url: function (value, row, index) {
                    return '<div class="input-group input-group-sm" style="width:250px;"><input type="text" class="form-control input-sm" value="' + value + '"><span class="input-group-btn input-group-sm"><a href="' + value + '" target="_blank" class="btn btn-default btn-sm"><i class="fa fa-link"></i></a></span></div>';
                },
                ip: function (value, row, index) {
                    return '<a class="btn btn-xs btn-ip bg-success"><i class="fa fa-map-marker"></i> ' + value + '</a>';
                },
                browser: function (value, row, index) {
                    //这里我们直接使用row的数据
                    return '<a class="btn btn-xs btn-browser">' + row.useragent.split(" ")[0] + '</a>';
                },
                custom: function (value, row, index) {
                    //添加上btn-change可以自定义请求的URL进行数据处理
                    return '<a class="btn-change text-success"  data-id="' + row.id + '"><i class="fa ' + (row.title == '' ? 'fa-toggle-on fa-flip-horizontal text-gray' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
            },
            events: {//绑定事件的方法
                ip: {
                    //格式为：方法名+空格+DOM元素
                    'click .btn-ip': function (e, value, row, index) {
                        e.stopPropagation();
                        var container = $("#table").data("bootstrap.table").$container;
                        var options = $("#table").bootstrapTable('getOptions');
                        //这里我们手动将数据填充到表单然后提交
                        $("form.form-commonsearch [name='ip']", container).val(value);
                        $("form.form-commonsearch", container).trigger('submit');
                        Toastr.info("执行了自定义搜索操作");
                    }
                },
                browser: {
                    'click .btn-browser': function (e, value, row, index) {
                        e.stopPropagation();
                        Layer.alert("该行数据为: <code>" + JSON.stringify(row) + "</code>");
                    }
                },
            }
        },
        table: {
            first: function () {
                // 表格1
                var table1 = $("#table1");
                Table.api.init({
                    extend: {
                        // index_url: 'purchase/requisition/index' + location.search,
                        add_url: 'purchase/requisition/adds',
                        // edit_url: 'purchase/requisition/edit',
                        // del_url: 'purchase/requisition/del',
                        // multi_url: 'purchase/requisition/multi',
                        // table: 'purchase_requisition',
                    }
                });
                $(".btn-add").data('area',["80%",'80%']);

                table1.bootstrapTable({
                    url: 'purchase/requisition/table1',
                    toolbar: '#toolbar1',
                    sortName: 'id',
                    search: false,
                    pageSize:5,
                    columns: [
                        [
                            {field: 'state', checkbox: true,class:'requisition_id'},
                            {field: 'id', title: 'ID'},
                            {field: 'createtime', title: __('Createtime')},
                            {field: 'number', title: __('Number')},
                            {field: 'nickname', title: __('Nickname')},
                            {field: 'name', title: __('Name')},

                            {
                                field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, buttons: [
                                    {
                                        name: 'log',
                                        title: '商品列表',
                                        text: '商品列表',
                                        icon: 'fa fa-list',
                                        classname: 'btn btn-primary btn-xs btn-click',
                                        click: function (e, data) {
                                            $("#myTabContent2 .form-commonsearch input[name='number']").val(data.id);
                                            $("#myTabContent2 .btn-refresh").trigger("click");
                                        }
                                    },{
                                        name: 'log',
                                        title: '选中',
                                        text: '选中',
                                        icon: 'fa fa-american-sign-language-interpreting',
                                        classname: 'btn btn-primary btn-xs btn-click',
                                        click: function (e, data) {
                                            var requisition_id =$(this).parents('tr').find('.requisition_id').html()
                                            parent.getrequisition(requisition_id);
                                            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                                            parent.layer.close(index);
                                        }
                                    }
                                ], formatter: Table.api.formatter.operate
                            }
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table1);
            },
            second: function () {
                // 表格2
                var table2 = $("#table2");
                table2.bootstrapTable({
                    url: 'purchase/requisition/table2',
                    extend: {
                        index_url: '',
                        add_url: '',
                        edit_url: '',
                        del_url: '',
                        multi_url: '',
                        table: '',
                    },
                    toolbar: '#toolbar2',
                    sortName: 'id',
                    search: false,
                    // commonSearch:false,
                    showExport: false,
                    showToggle: false,
                    showColumns: false,
                    columns: [
                        [
                            {field: 'state', checkbox: true,},
                            {field: 'id', title: 'ID', operate: false},
                            // {field: 'username', title: __('Nickname')},
                            {field: 'title', title: __('Title'), operate: false},
                            // {field: 'url', title: __('Url'), align: 'left', formatter: Table.api.formatter.url},
                            //自定义栏位,custom是不存在的字段
                            {field: 'number', title: __('请购单ID'),  formatter: Controller.api.formatter.custom,visible: false},
                            {field: 'specs', title: __('Specs'), operate: false},
                            {field: 'requisition_num', title: __('RequisitionNum'),  operate: 'RANGE', sortable: true, operate: false},
                            {field: 'price', title: __('Price'),  operate: 'RANGE', sortable: true, operate: false},
                            {field: 'remark', title: __('Remark'), operate: false},

                        ]
                    ]
                });

                // 为表格2绑定事件
                Table.api.bindevent(table2);
            }
        },
    };
    return Controller;
});